home *** CD-ROM | disk | FTP | other *** search
/ Java Certification Exam Guide / McGrawwHill-JavaCertificationExamGuide.iso / pc / Web Links and Code / code / chap22 / MultiChat.java < prev    next >
Encoding:
Java Source  |  1997-04-20  |  5.4 KB  |  203 lines

  1. import java.io.*;
  2. import java.net.*;
  3. import java.awt.*;
  4.  
  5. /**
  6.  * MultiChat -- A chat program between any number of clients.
  7.  *
  8.  * To run as a client, supply two parameters:
  9.  *   1. The name of the person to identify this user
  10.  *   2. the name the server:
  11.  *   java MultiChat Spielberg bluehorse.com
  12.  * or
  13.  *   java MultiChat Spielberg local       // to run locally
  14.  */
  15.  
  16. public class MultiChat extends Panel {
  17.     TextArea  receivedText;
  18.     Socket    sock;           // The communication socket.
  19.  
  20.     private GridBagConstraints c;
  21.     private GridBagLayout      gridBag;
  22.     private Frame              frame;
  23.     private Label              label;
  24.     private int                port = 5001;  // The default port.
  25.     private TextField          sendText;
  26.     private String             hostname;
  27.     private String             username;
  28.     private DataOutputStream   remoteOut;
  29.  
  30.     public static void main(String args[]) {
  31.        if (args.length != 2) {
  32.           System.out.println("format is: java MultiChat <username> <hostname>");
  33.           return;
  34.        }
  35.        
  36.        ExitFrame f = new ExitFrame(args[0]);
  37.  
  38.        MultiChat chat = new MultiChat(f, args[0], args[1]);
  39.        f.add("Center", chat);
  40.        f.resize(350, 200);
  41.        f.show();
  42.  
  43.        // Make the connection happen.
  44.        chat.client();        
  45.  
  46.     }
  47.    
  48.     public MultiChat(Frame f, String user, String host) {     
  49.         frame = f;
  50.         username = user;
  51.         hostname = host;
  52.  
  53.         // Build the user interface.
  54.         Insets insets = new Insets(10, 20, 5, 10); // bot, lf, rt, top
  55.         gridBag = new GridBagLayout();
  56.         setLayout(gridBag);
  57.  
  58.         c = new GridBagConstraints();
  59.  
  60.         c.insets = insets;
  61.         c.gridy = 0;
  62.         c.gridx = 0;
  63.  
  64.         label = new Label("Text to send:");
  65.         gridBag.setConstraints(label, c);
  66.         add(label);
  67.  
  68.         c.gridx = 1;
  69.  
  70.         sendText = new TextField(20);
  71.         gridBag.setConstraints(sendText, c);
  72.         add(sendText);
  73.  
  74.         c.gridy = 1;
  75.         c.gridx = 0;
  76.  
  77.         label = new Label("Text received:");
  78.         gridBag.setConstraints(label, c);
  79.         add(label);
  80.  
  81.         c.gridx = 1;
  82.  
  83.         receivedText = new TextArea(3, 20); 
  84.         gridBag.setConstraints(receivedText, c);
  85.         add(receivedText);
  86.     
  87.     }
  88.  
  89.     // As a client, we create a socket bound to the specified port,
  90.     // connect to the specified host, and then spawn a thread to 
  91.     // read data coming coming in over the network via the socket.
  92.  
  93.     private void client() {
  94.         try {
  95.             if (hostname.equals("local"))
  96.                hostname = null;
  97.  
  98.             InetAddress serverAddr = InetAddress.getByName(hostname);
  99.             sock = new Socket(serverAddr.getHostName(), port, true);           
  100.             remoteOut = new DataOutputStream(sock.getOutputStream());
  101.  
  102.             System.out.println("Connected to server " +
  103.                       serverAddr.getHostName() +
  104.                       " on port " + sock.getPort());
  105.  
  106.             new MultiChatReceive(this).start();
  107.  
  108.         } catch (IOException e) {
  109.             System.out.println(e.getMessage() +
  110.                ": Failed to connect to server.");
  111.         }
  112.     }
  113.  
  114.     // Send data out to the socket we're communicating with when
  115.     // the user hits enter in the text field.
  116.  
  117.     public boolean action(Event e, Object what) {
  118.  
  119.         if (e.target == sendText) {
  120.  
  121.            try {
  122.                // Send it.
  123.                remoteOut.writeUTF(username + ": " + sendText.getText());
  124.  
  125.                // Clear it.
  126.                sendText.setText("");
  127.            
  128.            } catch (IOException x) {
  129.                System.out.println(x.getMessage() +
  130.                   ": Connection to peer lost.");
  131.            }
  132.         }
  133.  
  134.         return super.action(e, what);
  135.     }
  136.  
  137.     protected void finalize() throws Throwable {
  138.        try {
  139.           if (remoteOut != null)
  140.              remoteOut.close();
  141.           if (sock != null)
  142.              sock.close();
  143.        } catch (IOException x) {
  144.        }
  145.        super.finalize();
  146.     }
  147.  
  148. }
  149.  
  150. /*
  151.  * ExitFrame allows us to exit when the user closes the frame.
  152.  */
  153. class ExitFrame extends Frame {
  154.    ExitFrame(String s) {
  155.       super(s);
  156.    }
  157.  
  158.    public boolean handleEvent(Event e) {
  159.        if (e.id == Event.WINDOW_DESTROY) {            
  160.             hide();
  161.             dispose();
  162.             System.exit(0);
  163.        }
  164.        return super.handleEvent(e);
  165.    }
  166. }
  167.  
  168. /*
  169.  * MultiChatReceive takes data sent on a socket and displays it in
  170.  * a text area. This receives it from the network.
  171.  */
  172. class MultiChatReceive extends Thread {
  173.     private MultiChat chat;
  174.  
  175.     MultiChatReceive(MultiChat chat) {
  176.         this.chat = chat;
  177.     }
  178.  
  179.     public synchronized void run() {
  180.         String s;
  181.         DataInputStream remoteIn = null;
  182.         try {
  183.             remoteIn = new DataInputStream(chat.sock.getInputStream());
  184.  
  185.             while (true) {
  186.                 s = remoteIn.readUTF();
  187.                 chat.receivedText.setText(s);    
  188.             }
  189.  
  190.         } catch (IOException e) {
  191.             System.out.println(e.getMessage() +
  192.                ": Connection to peer lost.");
  193.  
  194.         } finally {
  195.             try {
  196.                if (remoteIn != null)
  197.                   remoteIn.close();
  198.             } catch (IOException x) {
  199.             }
  200.          }
  201.     }
  202. }
  203.